package com.yhb.channel.impl.YPL;

import com.yhb.channel.provider.IUtilProvider;
import com.yhb.channel.utils.ConfigGetter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URISyntaxException;

@Data
@Service
public class YPLConfig {

    @Autowired
    private IUtilProvider utilProvider;
    // 配置
    private ConfigGetter configGetter;

    /* 协议支付绑卡 */
    private String bindCardUrl;
    /* 协议支付绑卡确认 */
    private String bindCardConfirmUrl;
    /* 协议支付交易 */
    private String payUrl;
    /* 单笔代付 */
    private String remitUrl;
    /* 公私钥 */
    private String publicKeyPath;
    private String privateKeyPath;
    private String privateKeyPassword;
    private String signNo; // 证书版本
    /* 商户号 */
    private String customerCode;

    /* 启动方法 */
    @PostConstruct
    private void init() {
        configGetter = new ConfigGetter("YPL", utilProvider);
        bindCardUrl = configGetter.get("bindCard");
        bindCardConfirmUrl = configGetter.get("bindCardConfirmUrl");
        payUrl = configGetter.get("protocolPayPre");
        remitUrl = configGetter.get("withdrawalToCard");
        publicKeyPath = configGetter.get("public_key");
        privateKeyPath = configGetter.get("private_key");
        privateKeyPassword = configGetter.get("private_key_pwd");
        signNo = configGetter.get("sign_no");
        customerCode = configGetter.get("customer_code");
    }

    public File getPublicKeyFile() {
        File keyFile = new File(publicKeyPath);
        if (keyFile.exists()) {
            return keyFile;
        } else {
            try {
                return new File(ClassLoader.getSystemResource(publicKeyPath).toURI());
            } catch (URISyntaxException e) {
                throw new YPLException(YPLConstant.ENCRYPT_OR_SIGN_ERROR, "公钥配置路径异常", e);
            }
        }
    }

    public File getPrivateKeyFile() {
        File keyFile = new File(privateKeyPath);
        if (keyFile.exists()) {
            return keyFile;
        } else {
            try {
                return new File(ClassLoader.getSystemResource(privateKeyPath).toURI());
            } catch (Exception e) {
                throw new YPLException(YPLConstant.ENCRYPT_OR_SIGN_ERROR, "私钥配置路径异常", e);
            }
        }
    }
}
